import 'package:flutter/material.dart';
import 'package:flutter_yn_goods/base/controller/base_list_more_controller.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/pages/mine_visit/model/model_visit_list.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/http/http_export.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:get/get.dart';

class MineVisitLogic extends BaseListMoreController {
  // tag
  static const String tag = 'MineVisitLogic';

  // 是否处于管理模式
  var isManageMode = false.obs;

  // 是否全选
  var isAllSelected = false.obs;

  // 选中的足迹商品数量
  var selectedCount = 0.obs;

  // 足迹商品总数
  var totalCount = 0.obs;
  
  // 按日期分组的数据
  var groupedData = <String, List<ModelVisitList>>{}.obs;

  @override
  void onInit() {
    super.onInit();
    // pageSize = 10;
  }
  
  // 更新分组数据
  void _updateGroupedData() {
    groupedData.clear();
    for (var item in list) {
      var visitItem = item as ModelVisitList;
      String timeKey = visitItem.timeKey ?? '';
      
      if (timeKey.isNotEmpty) {
        if (!groupedData.containsKey(timeKey)) {
          groupedData[timeKey] = [];
        }
        visitItem.isSelected = false; // 确保初始状态为未选中
        groupedData[timeKey]!.add(visitItem);
      }
    }
    update();
  }

  // 切换管理模式
  void toggleManageMode() {
    isManageMode.value = !isManageMode.value;
    if (!isManageMode.value) {
      // 退出管理模式时，取消所有选择
      _resetSelections();
    }
  }

  // 切换选择状态
  void toggleItemSelection(ModelVisitList item) {
    item.isSelected = !(item.isSelected ?? false);
    _updateSelectionStatus();
    update();
  }

  // 切换全选状态
  void toggleSelectAll() {
    isAllSelected.value = !isAllSelected.value;
    
    groupedData.forEach((timeKey, items) {
      for (var item in items) {
        item.isSelected = isAllSelected.value;
      }
    });
    
    _updateSelectionStatus();
    update();
  }

  // 更新选择状态
  void _updateSelectionStatus() {
    int count = 0;
    int totalItems = 0;
    
    groupedData.forEach((timeKey, items) {
      for (var item in items) {
        totalItems++;
        if (item.isSelected ?? false) {
          count++;
        }
      }
    });
    
    selectedCount.value = count;
    isAllSelected.value = totalItems > 0 && count == totalItems;
  }

  // 重置选择状态
  void _resetSelections() {
    groupedData.forEach((timeKey, items) {
      for (var item in items) {
        item.isSelected = false;
      }
    });
    
    selectedCount.value = 0;
    isAllSelected.value = false;
  }

  // 获取选中的商品ID列表
  List<dynamic> getSelectedIds() {
    List<dynamic> ids = [];
    
    groupedData.forEach((timeKey, items) {
      for (var item in items) {
        if (item.isSelected ?? false) {
          ids.add(item.productId);
        }
      }
    });
    
    return ids;
  }

  // 批量删除足迹
  Future<bool> batchDeleteVisit() async {
    List<dynamic> selectedIds = getSelectedIds();
    if (selectedIds.isEmpty) {
      LoadingUtils.showToast(LocaleKeys.please_select_items.tr);
      return false;
    }

    Map<String, dynamic> params = {
      'ids': selectedIds,
      'type': AppUserManager().isLeader() ? 'leader' : 'user',
      'id': AppUserManager().uid,
    };

    HttpResponse response =
        await HttpManager().post('api/user/visit', params: params);
    if (response.isSuccess) {
      // 删除成功后，从列表中移除选中的项
      groupedData.forEach((timeKey, items) {
        items.removeWhere((item) => (item.isSelected ?? false));
      });
      
      // 移除空的日期组
      groupedData.removeWhere((key, value) => value.isEmpty);
      
      _resetSelections();
      update();
      refresh();
      return true;
    }

    return false;
  }

  @override
  Future<List> loadData() async {
    Map<String, dynamic> params = {
      'page': pageNum,
      'limit': pageSize,
      'uid': AppUserManager().uid,
      'type': AppUserManager().isLeader() ? 'leader' : 'user',
    };

    HttpResponse response = await HttpManager().get(
      'api/user/visit_list',
      params: params,
    );

    if (response.isSuccess) {
      totalCount.value = response.data['count'] ?? 0;
      List<ModelVisitList> visitList = List<ModelVisitList>.from(
          (response.data['list'] as List)
              .map((e) => ModelVisitList.fromJson(e)));
      
      // 更新原始列表数据
      List<ModelVisitList> result = visitList;
      
      // 更新按日期分组的数据
      if (pageNum == 1) {
        list.clear();
        groupedData.clear();
      }
      
      list.addAll(result);
      _updateGroupedData();
      
      return result;
    }

    return [];
  }
}
